//
//  InvestManageViewController.m
//  Kjs-iOS
//
//  Created by 江伟 on 16/7/5.
//  Copyright © 2016年 jmhz. All rights reserved.
//

#import "InvestManageViewController.h"
#import "InvestRecordTableViewCell.h"
#import "InvestItemTableViewCell.h"
#import "UploadTransferViewController.h"
#import "AppDelegate.h"
#import "KJSRequest.h"
#import "TransverseSelectView.h"
#import <MJRefresh.h>

#define screenW [[UIScreen mainScreen] bounds].size.width //屏幕宽度
#define screenH [[UIScreen mainScreen] bounds].size.height //屏幕高度
@interface InvestManageViewController () <UITableViewDataSource,UITableViewDelegate>

@property (nonatomic,assign) int startPos;
@property (nonatomic,assign) int length;
@property (nonatomic,strong) NSMutableArray *records;
@property (nonatomic,assign) int page;
@property (nonatomic,assign) int itemStatus;
@property (nonatomic,strong) NSMutableArray *items;

@property (nonatomic,strong) NSData *imageData;
@property (nonatomic,strong) NSString *imageUrl;

@property (weak, nonatomic) IBOutlet TransverseSelectView *transverseView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *topDis;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *tableVTopDis;

@end

@implementation InvestManageViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.navigationItem setTitle:@"投资管理"];
    self.recordTableV.dataSource = self;
    self.recordTableV.delegate = self;
    if ([self.callViewType isEqualToString:@"investSuccess"]) {
        self.topDis.constant = self.navigationController.navigationBar.frame.size.height + 20;
        self.tableVTopDis.constant = -self.topDis.constant;
    }else{
        self.topDis.constant = 0;
        self.tableVTopDis.constant = 0;
    }
    self.transverseView.titleArray = @[@"投资记录",@"募集期中的项目",@"募集成功的项目",@"募集终止的项目"];
    self.transverseView.selectAction = ^(NSInteger selectLocation){
        [self configeration];
        NSLog(@"选择 %ld",(long)selectLocation);
        switch (selectLocation) {
            case 0:
                self.cellType = investRecord;
                [self GetInvestRecord];
                break;
            case 1:
                self.cellType = investRaisingItem;
                self.items = [[NSMutableArray alloc] init];
                self.itemStatus = 7;
                [self GetInvestItem];
                break;
            case 2:
                self.cellType = investRaisingItem;
                self.items = [[NSMutableArray alloc] init];
                self.itemStatus = 9;
                [self GetInvestItem];
                break;
            case 3:
                self.cellType = investRaisingItem;
                self.items = [[NSMutableArray alloc] init];
                self.itemStatus = 10;
                [self GetInvestItem];
                break;
            default:
                break;
        }
    };

    [self configeration];
    [self configurateTableView];
    
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self configeration];
    [self GetInvestRecord];
}
#pragma mark - configeration
- (void)configeration
{
    self.startPos = 0 ;
    self.length = 3;
    self.page = 1;
    self.records = [[NSMutableArray alloc] init];
    self.items = [[NSMutableArray alloc] init];
    self.cellNum = 0;
    
}

#pragma mark - custom method
- (void)configurateTableView {
    self.recordTableV.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(headerRefresh)];
    
    MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(footerRefresh)];
    [footer setTitle:@"上拉加载更多数据" forState:MJRefreshStateIdle];
    [footer setTitle:@"用力拉！~" forState:MJRefreshStatePulling];
    [footer setTitle:@"更新数据中~" forState:MJRefreshStateRefreshing];
    [footer setTitle:@"没有更多数据" forState:MJRefreshStateNoMoreData];
    
    self.recordTableV.mj_footer = footer;
    
    [self.recordTableV registerNib:[UINib nibWithNibName:@"InvestRecordView" bundle:nil] forCellReuseIdentifier:@"InvestRecordTableViewCell"];
    [self.recordTableV registerNib:[UINib nibWithNibName:@"InvestItemView" bundle:nil] forCellReuseIdentifier:@"InvestItemTableViewCell"];
}
- (void)GetInvestRecord
{
    if (CurentDelegate.account) {
        [KJSRequest GetUserOrderListWithPartyId:CurentDelegate.account.partyId IDisplayStart:self.startPos IDisplayLength:self.length ret:^(InvestRecordModel *model) {
            [self.records addObjectsFromArray:model.aaData];
            [(MJRefreshAutoNormalFooter *)self.recordTableV.mj_footer setTitle:([model.aaData count] < ROW_OF_EACH_PAGE)? @"没有更多数据了" :@"上拉加载更多数据" forState:MJRefreshStateIdle];
            self.cellNum = [self.records count];
            [self endRefresh];
            [self.recordTableV reloadData];
        }];
    }
}
- (void)GetInvestItem
{
    if (CurentDelegate.account) {
        [KJSRequest GetUserInvestItemWithPartyId:CurentDelegate.account.partyId page:self.page rows:self.length itemStatus:self.itemStatus ret:^(InvestItemModel *model) {
            [self.items addObjectsFromArray:model.investitems];
            [(MJRefreshAutoNormalFooter *)self.recordTableV.mj_footer setTitle:([model.investitems count] < ROW_OF_EACH_PAGE)? @"没有更多数据了" :@"上拉加载更多数据" forState:MJRefreshStateIdle];
            self.cellNum = [self.items count];
            [self endRefresh];
            [self.recordTableV reloadData];
        }];
    }
}

- (void)goUploadTransfer:(id)sender
{
    UIButton *btn = (UIButton *)sender;
    NSLog(@"跳转到上传支付凭证界面");
    UploadTransferViewController *uploadTransferVC = [[UIStoryboard storyboardWithName:@"Seconed" bundle:nil] instantiateViewControllerWithIdentifier:@"UploadTransferViewController"];
    uploadTransferVC.orderId = ((InvestRecord *)self.records[btn.tag]).orderId;
    uploadTransferVC.imageUrl = self.imageUrl;
    uploadTransferVC.addSuccess = ^(NSData *data,NSString *url){
        self.imageData = data;
        self.imageUrl = url;
    };
    uploadTransferVC.uploadeSuccess = ^(){
        [self configeration];
        [self configurateTableView];
    };
    if (self.topDis.constant > 0) {
        uploadTransferVC.ifAdjustContrain = YES;
    }
    [self displayViewController:uploadTransferVC];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSLog(@"cellnum=%ld",self.cellNum);
    return self.cellNum;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSLog(@"%ld",self.cellType);
    switch (self.cellType) {
        case investRecord:
        {
            InvestRecordTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"InvestRecordTableViewCell"];
            if ([self.records count]>indexPath.row) {
                InvestRecord *investRecord = self.records[indexPath.row];
                cell.investRecord = investRecord;
                cell.endTransferBtn.tag = indexPath.row;
                if ([investRecord.status isEqualToString:@"needvoucher"]) {
                    NSLog(@"设置事件");
                    [cell.endTransferBtn addTarget:self action:@selector(goUploadTransfer:) forControlEvents:UIControlEventTouchUpInside];
                }
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
            }
            return cell;
        }
            break;
        case investRaisingItem:
        {
            InvestItemTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"InvestItemTableViewCell"];
            if ([self.items count]>indexPath.row) {
                cell.item = self.items[indexPath.row];
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
            }
            return cell;
        }
            break;
        case investSuccessItem:
        {
            InvestItemTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"InvestItemTableViewCell"];
            if ([self.items count]>indexPath.row) {
                cell.item = self.items[indexPath.row];
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
            }
            return cell;
        }
            break;
        case investFailItem:
        {
            InvestItemTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"InvestItemTableViewCell"];
            if ([self.items count]>indexPath.row) {
                cell.item = self.items[indexPath.row];
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
            }
            return cell;
        }
            break;
        default:
        {
            InvestRecordTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"InvestRecordTableViewCell"];
            return cell;
        }
        break;
    }
}

#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

    
}

#pragma mark - refresh method
- (void)headerRefresh {
    [self configeration];
    switch (self.cellType) {
        case investRecord:
            [self GetInvestRecord];
            break;
        case investRaisingItem:
            [self GetInvestItem];
            break;
        case investSuccessItem:
            [self GetInvestItem];
            break;
        case investFailItem:
            [self GetInvestItem];
            break;
        default:
            [self GetInvestRecord];
            break;
    }
}

- (void)footerRefresh {
    switch (self.cellType) {
        case investRecord:
            self.startPos += self.startPos + self.length;
            [self GetInvestRecord];
            break;
        case investRaisingItem:
            self.page += 1;
            [self GetInvestItem];
            break;
        case investSuccessItem:
            self.page += 1;
            [self GetInvestItem];
            break;
        case investFailItem:
            self.page += 1;
            [self GetInvestItem];
            break;
        default:
            self.startPos += self.startPos + self.length;
            [self GetInvestRecord];
            break;
    }
}

- (void)endRefresh {
    [self.recordTableV.mj_header endRefreshing];
    [self.recordTableV.mj_footer endRefreshing];
}
@end
